import { Component } from '@angular/core';
import {IonicPage, Tabs, NavParams, NavController, LoadingController} from "ionic-angular";
import {TabsPage} from "../tabs/tabs";
import {UrlService} from "../../providers/urlService";
import {CommonUtilService} from "../../providers/commonUtilService";
import {IntfService} from "../../providers/intfService";
import {UtilService} from "../../providers/utilService";
import * as echarts from 'echarts';

declare var DateUtil: any;
declare let $:any;

@IonicPage()
@Component({
  selector: 'page-task',
  templateUrl: 'task.html'
})
export class TaskPage {
  canshowstachart:boolean=true;//是否显示图表
  totle:number;
  showcount: number=1;
  loading: any; //页面loading框变量
  taskinfo:any;
  custlist:any={list:[]};
  callStateList:any;
  myChart :any;
  seltabname:any;
  params = {
    Depart_Code: "-1",
    User_ID: "-1",
    Task_ID: "-1",
    order: "IN_Date desc",
    page: 1,
    fields: "*",
    seldatetype: 2,
    selstate: "count"
  }
  constructor(public navParams: NavParams,
              public navCtrl: NavController,
              private loadingCtrl: LoadingController,
              public commonUtil:CommonUtilService,
              public intfService: IntfService) {
    this.taskinfo =navParams.data;
  }

  ionViewDidLoad() {
    console.log("进入任务页面："+JSON.stringify(this.taskinfo));
    if(!this.taskinfo.Task_Name)this.toPage('TabsPage');

    this.callStateList=UtilService.getCallStateList();

    this.statesel  ('count');
    // 基于准备好的dom，初始化echarts实例
    this.myChart = echarts.init(document.getElementById('stachart'));

  }

  getchartoption(data){
    var option = {
      tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b}: {c} ({d}%)"
      },
      series: [
        {
          name:'拨打情况',
          type:'pie',
          selectedMode: 'single',
          radius: [0, '40%'],
          label: {
            normal: {
              position: 'inner'
            }
          },
          data:[
            {value:data.callstate0, name:'未拨打'},
            {value:data.callstate1, name:'已拨打' }
          ]
        },
        {
          name:'跟踪情况',
          type:'pie',
          radius: ['40%', '65%'],
          data:[
            {value:data.callstate0, name:'未拨打'},
            {value:data.followState0, name:'未标记'},
            {value:data.followState1, name:'无意向'},
            {value:data.followState2, name:'待跟进'},
            {value:data.followState3, name:'已成交'}
          ]
        }
      ]
    };

    return option;
  }
  loadCustlist  () {
    console.log('获取任务列表:querytasklist');
    this.loading =  this.commonUtil.showLoading({'content':'获取数据...', 'enableBackdropDismiss':true, 'dismissOnPageChange':false, 'duration':10000});
    this.showcount = 0;
    this.params.page = 1;//刷新显示第一页
    this.params.order = 'Call_State asc';
    this.params.Task_ID = this.taskinfo.Task_ID.trim();

    this.intfService.getReq(UrlService.url_taskcust()+this.taskinfo.Task_ID.trim()+'/', this.params, true).then((data) => {

      this.custlist.list =[];
       for (var i = 0; i < data.list.length; i++) {
         this.makeshowdata(data.list[i]);
        this.showcount++;
      }
      this.custlist = data ;//成员类型
      this.totle=this.custlist[this.params.selstate];

      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption( this.getchartoption(data));



      this.loading.dismiss();
    }).catch((error) => {
      this.loading.dismiss();
      this.commonUtil.showAlert({title:'温馨提示',message:'获取任务客户列表失败！'});
      console.log("获取任务客户列表失败:"+JSON.stringify(error));
    });


  }

  loadMoreCustlist   () {
    this.params.page ++;
    this.params.order = 'Call_State asc';
    console.log('获取更多任务列表:querytasklist');
    this.loading =  this.commonUtil.showLoading({'content':'获取数据...', 'enableBackdropDismiss':true, 'dismissOnPageChange':false, 'duration':10000});

    this.intfService.getReq(UrlService.url_taskcust()+this.taskinfo.Task_ID.trim()+'/', this.params, true).then((data) => {
      if (data.list.length > 0) {
        for (var i = 0; i < data.list.length; i++) {
          this.makeshowdata(data.list[i]);
          this.custlist.list.push(data.list[i]);
          this.showcount++;
        }
      }

      this.loading.dismiss();
    }).catch((error) => {
      this.loading.dismiss();
      this.commonUtil.showAlert({title:'温馨提示',message:'获取任务客户列表失败！'});
      console.log("获取任务客户列表失败:"+JSON.stringify(error));
    });


  }

   makeshowdata(data){
     data.laststartdate = DateUtil.timestamp2Time(data.laststartdate);
     data.Call_State_Str = UtilService.getCallType(data.Call_State.trim());
     data.Follow_State_Str = UtilService.getFollowType(data.Follow_State.trim());
     return data;
   }

   callSomething  (custphone) {
   /* $scope.params.Cust_Phone = custphone.trim();
    console.log("------------------------------$scope.params.Cust_Phone：" + custphone);
    var _params = {};
    _params['Depart_Code'] = $scope.params.Depart_Code;
    _params['User_ID'] = $scope.params.User_ID;
    _params['Phone'] = $scope.params.Phone;
    _params['Task_ID'] = $scope.params.Task_ID;
    _params['Call_Phone'] = custphone;
    _params['Cust_Phone'] = custphone;
    _params['Call_Staff'] = $scope.params.User_ID;
    var nowdate=new Date();
    var extraInfo = cordova.require('com.onluy.plugins.telemanager.telemanager');
    extraInfo.DoSome('Tel', _params,
      function (message) {   },
      function (message) { alert(message); });
    window.open('tel:' + custphone);
    for (var i = 0; i < $scope.custinfo.list.length; i++) {
      var obj = $scope.custinfo.list[i];
      if (custphone.trim() == obj.Cust_Phone.trim() && $scope.params.Task_ID.trim() == obj.Task_ID.trim()) {
        $scope.custinfo.list[i].Call_State = '1';
        $scope.custinfo.list[i].Call_State_Str = get_calltagstr('1');
        $scope.custinfo.list[i].laststartdate = nowdate.format("yyyy-MM-dd hh:mm:ss");
        $scope.custinfo.list[i].cellcount =(
          $scope.custinfo.list[i].cellcount == null || $scope.custinfo.list[i].cellcount==''?
            1 : $scope.custinfo.list[i].cellcount+1
        );
        break;
      }
    }*/
  }

   follostateshow = function (info) {
     let itemlist: any = UtilService.getfollostate();
     let radioAlertParams: any = {};
     radioAlertParams.title = "【"+info.Cust_Name+"】打标";
     radioAlertParams.inputList = itemlist;
     radioAlertParams.cancelCallback = () => {
       console.log('取消');
     }
     radioAlertParams.successCallback = (data) => {
       if (info.Follow_State  && data ==  info.Follow_State ) {
         console.log('我啥都没选');
         return;
       }
       this.upfollostate   (info,data);
       console.log('你选择的跟进状态是：'+data);
       //this.querytasklist();//刷新任务列表
     }
     this.commonUtil.showRadioAlert(radioAlertParams);
  }

   statesel  ( field) {
    this.seltabname=field;
    this.params.selstate = field;
     this.loadCustlist  ();
  }

   fun_tasksel   (taskid) {
    /*$scope.params.Task_ID = taskid.trim();
    $scope.fun_statesel("count");*/
  }

   fun_datesel   (type) {
    /*$scope.seldatetype = type;
    $scope.seldatestr = getSeldatetypeStr(type);
    $scope.taskdateselmodal.hide();
    $scope.doRefresh();*/
  }


   upfollostate   (info,state) {
    var infoparams={Task_ID:info.Task_ID.trim(),
      Cust_Phone: info.Cust_Phone.trim(),
      Follow_State:info.Follow_State
    };
     this.intfService.getReq(UrlService.url_uptaskcust() , infoparams, true).then((data) => {
       console.log('跟新状态返回：' + JSON.stringify(data));
       if (data.success || data.success == 'true') {
         info.Follow_State = state;
         info.Follow_State_Str = UtilService.getFollowType('' + state);
       }
       else {
         this.commonUtil.showAlert({title:'温馨提示',message:'更新客户标记失败！'});
       }
     }).catch((error) => {
       console.log('更新标记异常：' + JSON.stringify(error));
       this.commonUtil.showAlert({title:'异常',message:'更新标记异常！'});
     });
  }

  selchartModal(){
    this.canshowstachart=!this.canshowstachart;
  }

  //跳转到页面
  toPage(pageName: any) {
    this.navCtrl.push(pageName, {
    });
  }
}
